package com.kkk.shop.back.interceptor;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kkk.shop.common.util.ConstantFinalUtil;
import com.kkk.shop.common.util.HttpUtil;
import com.kkk.shop.user.pojo.AAdmins;
import com.kkk.shop.user.service.IUserService;

/**
 * 登录拦截器
 * @author kkk
 * 
 * */
@Component("loginAuthInterceptor")
public class LoginAuthInterceptor extends HandlerInterceptorAdapter
{
	@Resource
	private IUserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		ConstantFinalUtil.loggerMsg.info("---- 商城登陆验证----");
		HttpSession session = request.getSession() ; 
		
		/* 从session中获取admins对象 */
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		if(admins != null)
		{
			/* 已经登陆 --- 放行*/
			return true ; 
		}
		
		/* 第一次登陆跳转和登陆成功后跳转,唯一不一样的是token,客户端是否需要跳转到用户中心登陆页面的标志就是:token */
		String token = request.getParameter("token") ; 
		/* 取最后一个token */
		/*String[] tokens = request.getParameterValues("token");
		token = tokens[tokens.length - 1] ;*/
		ConstantFinalUtil.loggerMsg.info("--token:{}--",token);
		
		/* 验证Token的合法性 */
		String requestURL = ConstantFinalUtil.BUNDLE.getString("users.center.validatorTokenUrl");
		HttpUtil httpUtil = new HttpUtil();
		
		/* 拼装JSON,验证token需要的JSON */
		/* {"version":"1","data":{"token":"40639117-f3fd-4151-bbdb-c47fb54623bf"}}
		 * */
		JSONObject requestJSON = new JSONObject() ; 
		requestJSON.put("version", "1");
		JSONObject dataJSON = new JSONObject();
		dataJSON.put("token", token);
		requestJSON.put("data", dataJSON);
		
		try
		{
			Map<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("json", requestJSON + "");
			String responseStr = httpUtil.methodPost(requestURL, Collections.EMPTY_MAP, paramsMap);
			ConstantFinalUtil.loggerMsg.info("-验证-token返回:{}--",responseStr);
			JSONObject responseJSON = (JSONObject) JSON.parse(responseStr);
			/* 处理token */
			if("0".equalsIgnoreCase(responseJSON.getString("code")))
			{
				/* 成功 */
				JSONObject dataResJSON = responseJSON.getJSONObject("data");
				if(dataResJSON.get("admins") != null)
				{
					/* token合法 */
					
					/* 将token对应的管理员信息放到session中 */
					JSONObject adminsJSON = (JSONObject) dataResJSON.get("admins");
					adminsJSON.put("token", token);
					
					//从session中取数据,存储到数据库中,并将adminJSON转化成AAdmins
					//如果是第一次登录则直接插入到数据库中;否则先从数据库中查询,再根据updateFlag进行修改
					Map<String,Object> paramMap=ConstantFinalUtil.getParamMap();
					paramMap.put("ssoId", adminsJSON.get("id"));
					admins=this.userService.queryOneAdminsService(paramMap);
					//标记是否第一次登录
					boolean updateFlag=true;
					if(admins==null)
					{
						admins=new AAdmins();
						admins.setCreateTime(new Date());
						//设置updateFlag为true代表需要插入数据库
						updateFlag=false;
					}
					//不管是否需要插入数据库都将adminsJSON转化成admins对象
					//要对admins重新赋值
					admins=admins.parseObject(adminsJSON);
					//更新上次登录时间
					admins.setUpdateTime(new Date());
					if(updateFlag)
					{
						this.userService.updateOneAdminService(admins);
					}else
					{
						this.userService.insertOneAdminService(admins);
					}
					//将
					session.setAttribute("admins", admins);
					return true ; 
				}
			}
		} catch (Exception e)
		{
			ConstantFinalUtil.loggerMsg.error("--报错了----",e);
		}
		
		/* 获取returnUrl:当前即将访问的url */
		String returnUrl = request.getRequestURL() + "";
		/* 获取?后面的内容 */
		String queryStr = request.getQueryString() ;
		if(queryStr == null)
		{
			queryStr = "" ; 
		}
		
		/* 拼装returnUrl */
		if(queryStr.length() > 0 )
		{
			returnUrl = returnUrl + "?" +  queryStr ;
		}
		ConstantFinalUtil.loggerMsg.info("--currUrl:{}--queryStr:{}",returnUrl,queryStr);
		
		/* 跳转到用户中心的登陆页面,并且将returnUrl带上去 */
		String usersCenterLoginUrl = ConstantFinalUtil.BUNDLE.getString("users.center.loginUrl") + "&returnUrl=" + URLEncoder.encode(returnUrl, "UTF-8") ;
		ConstantFinalUtil.loggerMsg.info("--usersCenterLoginUrl:{}",usersCenterLoginUrl);
		/* 客户端跳转 */
		response.sendRedirect(usersCenterLoginUrl);
		return false;
	}
}
